package com.gadgets.framework.common.util;

import com.gadgets.framework.common.constant.GadgetsExceptionConstant;
import com.gadgets.framework.common.exception.GadgetsValidateException;
import com.gadgets.framework.thread.event.GadgetsThreadTaskEvent;
import com.gadgets.framework.thread.pool.GadgetsThreadPool;
import com.gadgets.framework.thread.task.AbstractRunnable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author UncleXiu
 * @version V1.0.0
 * @data 2020-09-21
 *
 */
public class ThreadTaskUtil {

    private static final Logger logger = LoggerFactory.getLogger(ThreadTaskUtil.class);

    /**
     * 系统通用线程池
     */
    private static final GadgetsThreadPool pool;

    static {
        pool = new GadgetsThreadPool(20,20,5, TimeUnit.SECONDS, new LinkedBlockingQueue<>(),70,30);
        logger.info("系统线程池启动完成");
    }

    public static void startThreadPool(){
        if(null==pool){
            logger.warn("线程池已启动，无需再次启动");
        }
    }

    /**
     * 提交线程任务
     * @param runnable  线程任务
     */
    public static void submit(AbstractRunnable runnable){
        pool.submit(runnable);
    }

    /**
     * 事件发布
     * @param event     事件对象
     */
    public static void publishEvent(GadgetsThreadTaskEvent event){
        if(StringUtils.isEmpty(event.getTaskNo())){
            throw new GadgetsValidateException(GadgetsExceptionConstant.VALIDATE_ERROR,"事件的任务编号不能为空");
        }
        pool.publishEvent(event);
    }

}
